<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\api\controller\v3;


use app\Request;
use crmeb\services\app\MiniProgramService;
use crmeb\services\pay\Pay;
use think\facade\Db;
use app\services\car\BaseLogServices;
use app\model\car\CarOrder;
use app\model\car\CarOrderRerent;
use app\model\user\User;
use app\services\wechat\NotifyService;
/**
 * 支付回调
 * Class PayController
 * @package app\api\controller\v3
 */
class NotifyController
{

    /**
     * 支付回调 用于易宝支付回调
     * @param string $type
     * @return string|void
     * @throws \EasyWeChat\Core\Exceptions\FaultException
     */
    public function notify(string $type)
    {
        switch (urldecode($type)) {
            case 'alipay':
                /** @var Pay $pay */
                $pay = app()->make(Pay::class, ['ali_pay']);
                return $pay->handleNotify();
            case 'v3wechat':
                return app()->make(Pay::class, ['v3_wechat_pay'])->handleNotify()->getContent();
            case 'routine':
                return MiniProgramService::handleNotify();
            case 'wechat':
                if (sys_config('pay_wechat_type')) {
                    /** @var Pay $pay */
                    $pay = app()->make(Pay::class, ['v3_wechat_pay']);
                } else {
                    /** @var Pay $pay */
                    $pay = app()->make(Pay::class);
                }
                return $pay->handleNotify()->getContent();
            case 'message':
                $jsonData = json_decode(file_get_contents('php://input'), true);
                //验签
                $json_data = json_encode($jsonData['otaContent'], JSON_UNESCAPED_UNICODE);
                if ($jsonData['otaContent']['status'] != "SUCCESS") {
                    return false;
                }
                $check_sign = verify($json_data, $jsonData['sign']);
                if ($check_sign != 1) {//验签失败
                    p("验签失败");
                    exit;
                    return false;
                }
                $updata = ['status' => 10, 'pay_time' => time(), 'pay_type' => 'weixin'];
                $order = Db::name('car_order')->where('order_no', $jsonData['otaContent']['orderNo'])->find();
                if (!$order) {
                    return false;
                }
                $res1 = Db::name('car_order')->where('id', $order['id'])->update($updata);
                $title = '用户支付订单';
                $user = Db::name('user')->where('uid', $order['uid'])->value('nickname');
                BaseLogServices::addLog($order['id'], 2, $title, 1, $order['uid'], $user, 3);
            case 'message2'://押金回调
                $jsonData = json_decode(file_get_contents('php://input'), true);
                //验签
                $json_data = json_encode($jsonData['otaContent'], JSON_UNESCAPED_UNICODE);
                if ($jsonData['otaContent']['status'] != "SUCCESS") {
                    return false;
                }
                $check_sign = verify($json_data, $jsonData['sign']);
                if ($check_sign != 1) {//验签失败
                    p("验签失败");
                    exit;
                    return false;
                }
                try {
                    $takeInfo = Db::name('car_order_take')->where(['take_no' => $jsonData['otaContent']['orderNo']])->find();
                    if (!$takeInfo) return true;
                    if ($takeInfo['deposit_pay_time'] > 0) return true;
                    $order = CarOrder::where(['take_id' => $takeInfo['id']])->find();
                    $order = $order ? $order->toArray() : [];
                    $userInfo = [];
                    if ($order) {
                        $userInfo = User::find($order['uid']);
                        $userInfo = $userInfo ? $userInfo->toArray() : [];
                    }
                    $services = app()->make(\app\services\car\OrderPayServices::class);
                    return $services->payDepositSuccess($takeInfo, PayServices::WEIXIN_PAY, ['trade_no' => $jsonData['otaContent']['orderNo']], $userInfo, 1);
                } catch (\Exception $e) {
                    return false;
                }
            default:
                if (strstr($type, 'allin') !== false) {
                    /** @var Pay $pay */
                    $pay = app()->make(Pay::class, ['allin_pay']);
                    return $pay->handleNotify($type);
                }
        }
    }


    /**
     * 微信服务商支付成功回调接口
     * 2023年12月12日11:53:08 用于服务商支付模式下的支付回调
     */
    public function wx_notify()
    {
        //获取返回json数据
        $getCallBackJson = file_get_contents('php://input');
//        $getCallBackJson = "{\"id\":\"05ee7306-abdc-53c5-ab91-248ac681bcd8\",\"create_time\":\"2024-01-31T15:02:46+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"TRANSACTION.SUCCESS\",\"summary\":\"支付成功\",\"resource\":{\"original_type\":\"transaction\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"NkJd55JGLSxUB8Z1E8glqs/DXuJNSHJPRv/nRe8OW91DTMzIWtvYcNIz8/+78j+LhoqIFYVAp+pOPWzOy1fRoQcDLzE5Wz14XV15mvfpAj7dChWnQsGxfACgmrJpvE/VPBdngCz5Vjv9jpydyJs+5su6so40WHzRS7TFR/6IELETEZSecVtvZS7fCzN1x4I1CEc+jj5cOkapxApgPKU+X+hLS3VBmrDYqmTuec4Q+kH48ddKan3eHLv6dwCSeF9waeFfbfaWuNiyd3Fh8A98ckU0iGTBgjapIlGpjKlgXc0QtZH+SKKYnZHw7laI7PfVFUjSbaJDSBbVKerAlkn9MoyKcn1jP2RV1xUiZEDSDzM2QeOdOJJgQfCt/+eSmHD0rE+ZjooPvXoVIEW8DQSX5OfDZ4NYfYTTfPCAxQuFzXyy6KX4eqyV5vnb62fDtB1506KzoicBj1wzT/cTAcz5CGt9kAW7Y+6xDuI6/AyY1hD4KqYY7lxagJpcdBvle/L/xEzGf4sVG0mUlh6q9qXH2jJFGhmCYLCSYCVyM5CIrpGOfTfH149wC0WSHuyytJ1o5GBz6eA6EMy21o2Gqa3n67fu10VOWQ2TA5qCPb0DkbivFKfxoylsMTPjb94RY569QpqrVJHNQIAQIBW9kAI2qneNHeCV+gATT5ZgcJByFs24LVxFmHivpHs0VQuHfXUuX+gvYMFmycaX5qf9yPcMcHKzIH04R1A=\",\"associated_data\":\"transaction\",\"nonce\":\"ykDbBIu5sKyj\"}}";
//        Db::name('test')->where('id',2)->update(['q'=>time()]);
//        Db::name('test')->where('id',1)->update(['q'=>$getCallBackJson]);
//        Db::name('test')->where('id',2)->update(['sign'=>222]);
        if(!$getCallBackJson){
            return "failure";
        }
        //转化为关联数组
        $getCallBackArray = json_decode($getCallBackJson, true);
        //获取需要解密字段
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        //执行解密
        $apiKey = sys_config('pay_weixin_key_v3');   //这里需要填写APIv3秘钥
        $getData = new NotifyService($apiKey);
        $resultJson = $getData->decryptToString($associatedData, $nonceStr, $ciphertext);

        //解密结果，为关联数组格式
        $resultArray = json_decode($resultJson, true);

        //交易成功
        if ($resultArray['trade_state'] === 'SUCCESS') {
            //这里填写交易成功的相关业务，如更新账单状态，其中可能需要用到的参数如下
            //$resultArray['out_trade_no']       商户订单号
            //$resultArray['transaction_id']     订单号
            //$resultArray['amount']['total']    订单金额
            Db::startTrans();
            try {
                $updata = ['status' => 10, 'pay_time' => time(), 'pay_type' => 'weixin','out_trade_no'=>$resultArray['transaction_id']];
                $resultArray['out_trade_no'] = explode('-',$resultArray['out_trade_no'])[0];
                $order = Db::name('car_order')->where('order_no', $resultArray['out_trade_no'])->find();
                if (!$order) {
                    return false;
                }
                $res1 = Db::name('car_order')->where('id', $order['id'])->update($updata);
                $title = '用户支付订单';
                $user = Db::name('user')->where('uid', $order['uid'])->value('nickname');
                //新增微信回调数据
                $this->add_wx_callback($resultArray,$order);
                BaseLogServices::addLog($order['id'], 2, $title, 1, $order['uid'], $user, 3);
                //新增订单流水2024年2月26日16:26:19
                BaseLogServices::add_order_flow($order);
                Db::commit();
                echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            } catch (DbException $e) {
                echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Error]]></return_msg></xml>';
            }
        }
        echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Error]]></return_msg></xml>';
    }


    //插入微信支付成功回调数据
    public  function add_wx_callback($resultArray,$order){
        $wx = Db::name('wx_callback_log')->where(['transaction_id'=>$resultArray['transaction_id'],'type'=>'pay','q'=>$resultArray['amount']['total']])->find();
        if(!$wx){
            Db::name('wx_callback_log')->insert(['wx'=>json_encode($resultArray),'add_time'=>time(),'type'=>'pay','transaction_id'=>$resultArray['transaction_id'],'order_id'=>$order['id'],'q'=>$resultArray['amount']['total']]);
        }
        return [];
    }
    //插入微信退款成功回调数据
    public  function add_wx_refund_callback($resultArray){
        $wx = Db::name('wx_callback_log')->where(['transaction_id'=>$resultArray['transaction_id'],'type'=>'refund'])->find();
        if(!$wx){
            $order_id = Db::name('car_order')->where('out_trade_no',$resultArray['transaction_id'])->value('id');
            Db::name('wx_callback_log')->insert(['order_id'=>$order_id,'wx'=>json_encode($resultArray),'add_time'=>time(),'type'=>'refund','transaction_id'=>$resultArray['transaction_id'],'q'=>$resultArray['amount']['total']]);
        }
        return [];
    }

    //退款回调地址
    public function refund_notify(){
        Db::name('test')->where('id',2)->update(['sign'=>time()]);
        //获取返回json数据
        $notifiedData = file_get_contents('php://input');
        if(!$notifiedData){
            return "failure";
        }
        //转化为关联数组
        $getCallBackArray = json_decode($notifiedData, true);
        //获取需要解密字段
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        //执行解密
        $apiKey = sys_config('pay_weixin_key_v3');   //这里需要填写APIv3秘钥
        $getData = new NotifyService($apiKey);
        $resultJson = $getData->decryptToString($associatedData, $nonceStr, $ciphertext);
        //解密结果，为关联数组格式
        $resultArray = json_decode($resultJson, true);
        //交易成功
        if ($resultArray['refund_status'] === 'SUCCESS') {
            $transaction_id=$resultArray['transaction_id']; //退款单号
            //新增微信回调数据
            $this->add_wx_refund_callback($resultArray);
            /*业务处理*/
            return json(['code'=>'SUCCESS','message'=>'成功']);
        }
    }




}
